//
//  XDImageDetailView.m
//  XDUI
//
//  Created by xieyajie on 13-10-25.
//  Copyright (c) 2013年 XD. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "XDImageDetailView.h"

#import "UIImage+Category.h"
#import "NSString+Category.h"
#import "SCGIFImageView.h"
#import "TKProgressCircleView.h"

//#import "ImageCache.h"
//#import "TKAlertCenter.h"
//#import "XDFileManager.h"
//#import "Reachability.h"
//#import "XDCategory.h"
//#import "RequestCenter.h"
//#import "ViewManager.h"

//#import "TKProgressBarView.h"
//#import "XDMP3Player.h"
//#import "XDMP4Player.h"
//#import "XDButton.h"

@interface XDImageDetailView ()
{
    UITapGestureRecognizer *doubleTapGR;//双击手势
    UITapGestureRecognizer *tapGR;
    UIImageView *borderImageView;//边框视图
    UIButton *menuButton;//菜单按钮
    UIImage *moreImage;//更多菜单按钮图片
    UIImage *saveImage;//保存菜单按钮图片
    BOOL isLookOriginalImage;//显示保存菜单按钮的图片
    TKProgressCircleView *progressBar;//进度条视图
    
    
    UILabel   *progressLabel;//进度条标签
    UIView *loadingView;//转圈等待视图
    UIScrollView *contentScrollView;//主滚动面板
    SCGIFImageView *gifImageView;//显示GIF图片的视图
    float   width;
    float   height;
    NSMutableData *receivedData;//下载原图过程中的已接收数据
    CGRect oldFrame;
    CGPoint touchPoint;//触摸点
    float fileLength;
    CGSize mainSize;
    
    UIImage *dealImage;
    NSString *dealImageURL;
    
//    ASIHTTPRequest *httpRequest ;
    
    
    float scale;       // 默认2.0
    BOOL isWidthImage; // 默认YES
    BOOL isDownload;   // 默认NO
    UIImageView *tempImageView; //
    
    CGRect adaptionFrame; //图片自适应大小
    
    UIImageView *_gifTagImageView;
}

@property (strong, nonatomic) UIWindow *topLevelWindow;

@end

@implementation XDImageDetailView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        mainSize   = [UIScreen mainScreen].bounds.size;
        touchPoint = CGPointMake(mainSize.width/2, mainSize.height/2 - 10);
        moreImage  = [UIImage imageNamed:@"image_more_image.png"];
        saveImage  = [UIImage imageNamed:@"image_save_image.png"];
        isLookOriginalImage  = NO;
        self.downloadFileDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/ImageCache"];
        self.isAdaption = NO;
        self.thumbMode  = YES;
        self.mediaType  = XDMediaTypeImage;
        scale           = 2.0;
        isWidthImage    = YES;
        tempImageView   = nil;
        
        _thumbnailImageView                        = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _thumbnailImageView.clipsToBounds          = YES;
        _thumbnailImageView.userInteractionEnabled = YES;
        _thumbnailImageView.contentMode            = UIViewContentModeScaleAspectFit;
        [self addSubview:_thumbnailImageView];
        [self sendSubviewToBack:_thumbnailImageView];
    }
    return self;
}

- (void)dealloc
{
    _thumbnailImageView = nil;
    borderImageView     = nil;
    _borderImage        = nil;
    _originalURL        = nil;
    _downloadFileDir    = nil;
}

- (UIWindow *)topLevelWindow
{
    if (_topLevelWindow == nil) {
        _topLevelWindow = [[UIWindow alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame];
        _topLevelWindow.backgroundColor = [UIColor blackColor];
    }
    return _topLevelWindow;
}

- (void)setShowBorder:(BOOL)showBorder
{
    if (showBorder) {
        _thumbnailImageView.layer.borderWidth = 2;
        _thumbnailImageView.layer.borderColor = [UIColor whiteColor].CGColor;
    } else {
        _thumbnailImageView.layer.borderWidth = 0;
        _thumbnailImageView.layer.borderColor = nil;
    }
}

- (void)setIsAdaption:(BOOL)isAdaption
{
    _isAdaption = isAdaption;
    if (!_isAdaption) {
        _thumbnailImageView.contentMode            = UIViewContentModeScaleAspectFill;
    }
}

//缩略图
- (void)setImage:(UIImage *)image
{
    _image = image;
    _thumbnailImageView.image = _image;
    float appendix_x = 0;
    float appendix_y = 0;
    CGSize size = CGSizeZero;
    if (_mediaType == XDMediaTypeMood) { //心情--附件
        size = [_image sizeOfScaleToFit:MOOD_IMAGE_SIZE];
    } else if (_mediaType == XDMediaTypeAudio) { //音频--附件
        size = AUDIO_IMAGE_SIZE;
    } else {
        if (_thumbMode) { //缩略图模式
            if (_isAdaption) { //--附件
                size       = [_image sizeOfScaleToFit:THUMB_IMAGE_SIZE];
                appendix_y = THUMB_IMAGE_SIZE.height/2 - size.height/2;
            } else { //--其他图片 非附件
                size       = [_image sizeOfScaleToFit:self.frame.size];
                appendix_y = self.frame.size.height/2 - size.height/2;
            }
        } else { //全图模式
            if (_isAdaption) { //--附件
                size       = [_image sizeOfScaleToFit:BIG_IMAGE_SIZE];
                appendix_y = BIG_IMAGE_SIZE.height/2 - size.height/2;
                appendix_x = BIG_IMAGE_SIZE.width/2 - size.width/2;
            } else { //--其他图片 非附件
                size       = [_image sizeOfScaleToFit:self.frame.size];
                appendix_y = self.frame.size.height/2 - size.height/2;
                appendix_x = self.frame.size.width/2 - size.width/2;
            }
        }
    }
    adaptionFrame = CGRectMake(appendix_x, appendix_y, size.width, size.height);
    oldFrame      = adaptionFrame;
    if (_isAdaption) {
        _thumbnailImageView.frame = adaptionFrame;
    }
}

- (void)setMediaType:(XDMediaType)mediaType
{
    _mediaType = mediaType;
    float tempWidth = 30;
    if (!_thumbMode) {
        tempWidth =  60;
    }
    if (_mediaType == XDMediaTypeGIF) {
        if (_showGifTag) {
            [self showGifTagView];
        } else {
            [_gifTagImageView removeFromSuperview];
            _gifTagImageView = nil;
        }
    } else if (_mediaType == XDMediaTypeVideo) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, tempWidth, tempWidth)];
        imageView.clipsToBounds = YES;
        imageView.userInteractionEnabled = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.center = _thumbnailImageView.center;
        imageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
        [_thumbnailImageView addSubview:imageView];
        imageView.image = [UIImage imageNamed:@"audio_play_btn.png"];
    } else if (_mediaType == XDMediaTypeAudio) {
        UIButton *audioButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 60.0, 60.0)];
        [audioButton setImage:[UIImage imageNamed:@"audio_audio.png"] forState:UIControlStateNormal];
        [audioButton addTarget:self action:@selector(playAudio) forControlEvents:UIControlEventTouchUpInside];
        [_thumbnailImageView addSubview:audioButton];

        NSString *durationString = @"";
        if (_mediaDuration >= 60.0) {
            durationString = [NSString stringWithFormat:@"%.f分%d秒", _mediaDuration / 60, (NSInteger)_mediaDuration % 60];
        } else if (_mediaDuration > 0.0) {
            durationString = [NSString stringWithFormat:@"%.f秒", _mediaDuration];
        }
        NSLog(@"%@", durationString);
        UILabel *durationLabel = [[UILabel alloc] initWithFrame:CGRectMake(65.0, 0.0, AUDIO_IMAGE_SIZE.width - 65.0, AUDIO_IMAGE_SIZE.height)];
        durationLabel.backgroundColor = [UIColor clearColor];
        durationLabel.textColor = [UIColor grayColor];
        durationLabel.font = [UIFont systemFontOfSize:14.0];
        durationLabel.text = durationString;
        [_thumbnailImageView addSubview:durationLabel];
    }
}

- (void)setShowGifTag:(BOOL)showGifTag
{
    _showGifTag = showGifTag;
    
    if (_showGifTag) {
        [self showGifTagView];
    } else {
        [_gifTagImageView removeFromSuperview];
        _gifTagImageView = nil;
    }
}

//gif标记
- (void)showGifTagView
{
    if (_mediaType == XDMediaTypeGIF) {
        if (!_gifTagImageView) {
            _gifTagImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
            _gifTagImageView.clipsToBounds = YES;
            _gifTagImageView.userInteractionEnabled = YES;
            _gifTagImageView.contentMode = UIViewContentModeScaleToFill;
        }
        
        float tempWidth = 30;
        if (!_thumbMode) {
            tempWidth =  60;
        }
        _gifTagImageView.frame = CGRectMake(2, 2, tempWidth, tempWidth);
        _gifTagImageView.image = [[UIImage imageNamed:@"image_gif"] resizableImageWithCompatibleCapInsets:UIEdgeInsetsMake(tempWidth, tempWidth, 5, 5) resizingMode:UIImageResizingModeStretch];
        [_thumbnailImageView addSubview:_gifTagImageView];
    }
}

//边框
- (void)setBorderImage:(UIImage *)borderImage
{
    _borderImage = borderImage;
    if (!borderImageView) {
        borderImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        borderImageView.image = [_borderImage resizableImageWithCompatibleCapInsets:UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0) resizingMode:UIImageResizingModeStretch];
        borderImageView.userInteractionEnabled = YES;
        [self addSubview:borderImageView];
    }
}

//支持初始化 即看原图 （GIF）
- (void)setShowOriginal:(BOOL)showOriginal
{
    _showOriginal = showOriginal;
    if (_showOriginal) {
        
    }
}

//touch事件
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint firstPoint = [touch locationInView:touch.window];
    CGPoint selfPoint = [touch locationInView:_thumbnailImageView];
    int offX = selfPoint.x - oldFrame.size.width/2.0;
    int offY = selfPoint.y - oldFrame.size.height/2.0;
    
    touchPoint = CGPointMake(firstPoint.x - offX, firstPoint.y - offY);

    if (_mediaType == XDMediaTypeVideo) { //视频
        if (_audioPath.length) {
//            [XDMP4Player play:_audioPath];
        }
    } else if (_mediaType == XDMediaTypeAudio) {//音频
        //点击按钮播放，触控不播放
//        if (_audioPath.length) {
//            [XDMP3Player play:_audioPath];
//        }
    } else { //图片
        if (_originalURL.length) {
            [self enterFullScreen];
        }else if (_originalImage) {
            [self enterFullScreen];
        } else if (_normalURL.length) {
            [self enterFullScreen];
        } else if (_normalImage) {
            [self enterFullScreen];
        }
    }
}

//进入全屏
- (void)enterFullScreen
{
    if (contentScrollView) {
        return;
    }
    _image = _thumbnailImageView.image;
    tempImageView = [[UIImageView alloc] init];
    tempImageView.frame = adaptionFrame;
    tempImageView.image = _image;
    tempImageView.clipsToBounds = _thumbnailImageView.clipsToBounds;
    tempImageView.userInteractionEnabled = _thumbnailImageView.userInteractionEnabled;
    tempImageView.contentMode = UIViewContentModeScaleAspectFit;
    
    contentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, mainSize.width, mainSize.height)];
    contentScrollView.delegate = self;
    [contentScrollView addSubview:tempImageView];
    
    [self.topLevelWindow addSubview:contentScrollView];
    self.topLevelWindow.backgroundColor = [UIColor blackColor];
    self.topLevelWindow.windowLevel = UIWindowLevelAlert;
    [self.topLevelWindow makeKeyAndVisible];
    
    //保存图片按钮
    menuButton = [[UIButton alloc] initWithFrame:CGRectMake(mainSize.width - 69, mainSize.height - 40, 59, 30)];
    [self.topLevelWindow addSubview:menuButton];
    
    CGFloat factor = 1;//图片宽高比参数
    if (_image != nil) {
        factor = _image.size.width / _image.size.height;
    }
    CGFloat x;
    CGFloat y;
    if (factor > mainSize.width/mainSize.height) {//图片属于宽图，宽调整为320.0
        width  = mainSize.width;
        height = mainSize.width/factor;
        x = 0.0;
        y = mainSize.height/2 - height/2.0;
    } else {//图片属于高图，高调整为480.0
        width  = mainSize.width;
        height = mainSize.width/factor;
        x = mainSize.width/2 - width/2.0;
        y = 0.0;
    }
    
    tempImageView.center = touchPoint;
    
    [UIView animateWithDuration:0.4 animations:^{
        tempImageView.frame = CGRectMake(x, y, width, height);
    } completion:^(BOOL finished) {
        [self loadImage];//加载图片
    }];
    
    //添加手势
    doubleTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapImage)];
    doubleTapGR.numberOfTapsRequired = 2;
    doubleTapGR.numberOfTouchesRequired = 1;
    [contentScrollView addGestureRecognizer:doubleTapGR];
    
    tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(quitFullScreen)];
    tapGR.numberOfTapsRequired = 1;
    tapGR.numberOfTouchesRequired = 1;
    [tapGR requireGestureRecognizerToFail:doubleTapGR];//遇到双击事件时，屏蔽单击事件
    [contentScrollView addGestureRecognizer:tapGR];
}

//退出全屏
- (void)quitFullScreen
{
    tempImageView.image = _image;
    [contentScrollView removeGestureRecognizer:doubleTapGR];
    [contentScrollView removeGestureRecognizer:tapGR];
//    if ([httpRequest isExecuting]) {
//        [httpRequest clearDelegatesAndCancel];
//    }
//    httpRequest.delegate = nil;
//    httpRequest = nil;
    
    [self removeDownloadView];
    self.topLevelWindow.backgroundColor = [UIColor clearColor];
    //移除视图
    [menuButton removeFromSuperview];
    menuButton = nil;
    
    float temp_x =  touchPoint.x - oldFrame.size.width/2 + contentScrollView.contentOffset.x;
    float temp_y =  touchPoint.y - oldFrame.size.height/2 + contentScrollView.contentOffset.y;
    
    [UIView animateWithDuration:0.4 animations:^{
        tempImageView.frame = CGRectMake(temp_x, temp_y, oldFrame.size.width, oldFrame.size.height);
        gifImageView.frame = CGRectMake(0, 0, oldFrame.size.width, oldFrame.size.height);
    } completion:^(BOOL finished) {
        if (_mediaType == XDMediaTypeGIF) {//GIF图片
            [gifImageView removeFromSuperview];
            gifImageView = nil;
        }
        [tempImageView removeFromSuperview];
        tempImageView = nil;
        self.topLevelWindow.windowLevel = -1;
        [[[[UIApplication sharedApplication] delegate] window] makeKeyAndVisible];
        [contentScrollView removeFromSuperview];
        contentScrollView.delegate = nil;
        contentScrollView = nil;
    
        _image = nil;
        //_originalImage = nil;传参的方式查看原图时，此处赋值导致无法第二次看大图
    }];
}

//加载图片
- (void)loadImage
{
    //存储原图图片
    NSString *filePath = nil;
    if (_originalImage == nil) {
        if (_originalURL.length) {
            if ([_originalURL hasPrefix:NSHomeDirectory()]) {
                _originalImage = [UIImage imageWithContentsOfFile:_originalURL];
            } else {
                filePath = [_downloadFileDir stringByAppendingPathComponent:_originalURL.GBKEncodedString];
                dealImageURL = _originalURL;
                if (_mediaType == XDMediaTypeGIF) {
                    if (gifImageView == nil) {
                        gifImageView = [[SCGIFImageView alloc] initWithGIFFile:filePath];
                        gifImageView.contentMode = UIViewContentModeScaleAspectFit;
                    }
                    if (gifImageView.isGIF) {
                        _originalImage = gifImageView.image;
                    } else {
                        gifImageView = nil;
                        _originalImage = nil;
                    }
                } else {
                    _originalImage = [UIImage imageWithContentsOfFile:filePath];
                }
            }
        }
    }
    
    if (_originalImage == nil) {//加载原图
        if (isLookOriginalImage) { //查看原图
            dealImage = nil;
            if (_originalURL.length) {
                dealImageURL = _originalURL;
            } else {
                filePath = nil;
            }
        } else if (_mediaType == XDMediaTypeGIF) {//GIF图片 不需要加载中图
            if (_originalURL.length) {
                filePath = [_downloadFileDir stringByAppendingPathComponent:_originalURL.GBKEncodedString];
                dealImageURL = _originalURL;
            } else {
                filePath = nil;
            }
        } else { //去加载中图
            if (_normalImage == nil) {//加载中图 模式
                if (_normalURL.length) {
                    filePath = [_downloadFileDir stringByAppendingPathComponent:_normalURL.GBKEncodedString];
                    _normalImage = [UIImage imageWithContentsOfFile:filePath];
                }
            }
            
            if (_normalImage == nil) { //没有中图缓存
                if (_normalURL.length) { //没有中图下载路径
                    dealImageURL = _normalURL;
                    [menuButton setBackgroundImage:moreImage forState:UIControlStateNormal];
                    [menuButton addTarget:self action:@selector(menuAction) forControlEvents:UIControlEventTouchUpInside];
                } else { //没有中图下载路径 则去查找原图路径
                    if (_originalURL.length) {
                        isLookOriginalImage = YES;
                        filePath = [_downloadFileDir stringByAppendingPathComponent:_originalURL.GBKEncodedString];
                        dealImageURL = _originalURL;
                    } else {
                        filePath = nil;
                    }
                }
            } else { // 存在中图缓存
                dealImage = _normalImage;
                [menuButton setBackgroundImage:moreImage forState:UIControlStateNormal];
                [menuButton addTarget:self action:@selector(menuAction) forControlEvents:UIControlEventTouchUpInside];
            }
        }
    } else {
        dealImage = _originalImage;
        [menuButton setBackgroundImage:saveImage forState:UIControlStateNormal];
        [menuButton addTarget:self action:@selector(saveImage) forControlEvents:UIControlEventTouchUpInside];
    }
    
    isDownload = NO;
    if (dealImage == nil) {//未下载过图片,异步加载
        NSLog(@"begin download");
        if (filePath.length) {
            isDownload = YES;
            [self downloadImage:filePath];
        }
    } else {//下载过图片,从文件加载
        contentScrollView.maximumZoomScale = scale;
        contentScrollView.minimumZoomScale = 0.5;
        [self performSelector:@selector(showImage) withObject:nil afterDelay:0.1];//延迟加载,解决读取特大图时的卡顿
    }
}

- (void)downloadImage:(NSString *)filePath
{
    //判断filePath 路径的目录是否存在 不存在 则创建
    NSString *directoryPath = [filePath substringToIndex:filePath.length - [(NSString *)filePath.pathComponents.lastObject length]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
	if (![fileManager fileExistsAtPath:directoryPath]) {
		[fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
	}
    if (dealImageURL.isValidImageURL) {
        [self downloadOriginalRequest:filePath];
    } else {
        [self downloadNormalRequest:filePath];
    }
}

//中图请求下载
- (void)downloadNormalRequest:(NSString *)filePath
{
    loadingView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 100.0)];
    loadingView.center = self.center;
    loadingView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    loadingView.layer.cornerRadius = 6.0;
    
    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicatorView.center = CGPointMake(50, 50);
    [loadingView addSubview:activityIndicatorView];
    [activityIndicatorView startAnimating];
    
    [self.topLevelWindow addSubview:loadingView];
    NSLog(@"dealImageURL===%@",dealImageURL);
//    httpRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:dealImageURL]];
//    httpRequest.delegate = self;
//    [httpRequest setDownloadDestinationPath:filePath];
//    [httpRequest setTimeOutSeconds:300];//设置超时时间为30s
//    [httpRequest startAsynchronous];
}

//原图请求下载
- (void)downloadOriginalRequest:(NSString *)filePath
{
//    NSString *tempFilePath = [NSString stringWithFormat:@"%@.download",filePath];
    //添加进度条
    progressBar = [[TKProgressCircleView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    progressBar.center = CGPointMake(mainSize.width/2, mainSize.height/2);
    [self.topLevelWindow addSubview:progressBar];
    //添加进度条进度显示的标签
    progressLabel = [[UILabel alloc] initWithFrame:CGRectMake(mainSize.width/2 - 60, mainSize.height/2 + 20, 120, 20)];
    progressLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.75];
    progressLabel.layer.cornerRadius = 8;
    progressLabel.text = @"正在下载...";
    progressLabel.textColor = [UIColor whiteColor];
    progressLabel.textAlignment = NSTextAlignmentCenter;
    [self.topLevelWindow addSubview:progressLabel];
    
//    if ([httpRequest isExecuting]) {
//        [httpRequest clearDelegatesAndCancel];
//        httpRequest = nil;
//    }
//    NSLog(@"dealImageURL===%@",dealImageURL);
//    httpRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:dealImageURL]];
//    httpRequest.delegate = self;
//    [httpRequest setDownloadDestinationPath:filePath];
////    //这个文件已经被下载了一部分  断点续传
////    [httpRequest setTemporaryFileDownloadPath:tempFilePath];
////    [httpRequest setAllowResumeForFileDownloads:YES];
//    
//    [httpRequest setTimeOutSeconds:300];//设置超时时间为30s
//    [httpRequest setDownloadProgressDelegate:self];//设置进度条
//    [httpRequest startAsynchronous];
}

//取消下载请求
- (void)removeDownloadView
{
    [progressBar removeFromSuperview];
    progressBar = nil;
    [progressLabel removeFromSuperview];
    progressLabel = nil;
    [loadingView removeFromSuperview];
    loadingView = nil;
}

//菜单按钮事件
- (void)menuAction
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"查看原图",@"保存图片", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
}

/***********************
 actionSheet deletgate
 ***********************/
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != actionSheet.cancelButtonIndex) {
        switch (buttonIndex) {
            case 0:
                [self lookOriginalImage];
                break;
            case 1:
                [self saveImage];
                break;
            default:
                break;
        }
    }
}

//查看原图
- (void)lookOriginalImage
{
    [self removeDownloadView];
    isLookOriginalImage = YES;
    [contentScrollView setZoomScale:1 animated:YES];;
    [self loadImage];
}

/*******
 视图管理
 *******/
/*显示原图*/
- (void)showImage
{
	contentScrollView.multipleTouchEnabled = YES;
    menuButton.hidden = NO;
    if (isLookOriginalImage) {
        [menuButton setBackgroundImage:saveImage forState:UIControlStateNormal];
        [menuButton removeTarget:self action:@selector(menuAction) forControlEvents:UIControlEventTouchUpInside];
        [menuButton addTarget:self action:@selector(saveImage) forControlEvents:UIControlEventTouchUpInside];
    }
    //分为“宽图”、“高图”两种类型处理
    CGFloat factor = dealImage.size.width / dealImage.size.height;//图片宽高比参数
    CGFloat x;
    CGFloat y;
    if (factor > mainSize.width/mainSize.height) {//图片属于宽图，宽调整为320.0
        width = mainSize.width;
        height = mainSize.width/factor;
        x = 0.0;
        y = mainSize.height/2 - height/2.0;
        isWidthImage = YES;
    } else {//图片属于高图，高调整为480.0
        width = mainSize.width;
        height = mainSize.width/factor;
        x = 0.0;//mainSize.width/2 - width/2.0;
        y = 0.0;
        contentScrollView.contentSize = CGSizeMake(width, height);
        isWidthImage = NO;
    }

    tempImageView.frame = CGRectMake(x, y, width, height);
    //添加原图,初始化框架参数。头像gif待补充
    if (_mediaType == XDMediaTypeGIF) {//GIF图片
        tempImageView.image = nil;
        if (gifImageView == nil) {
            NSString *filePath = [_downloadFileDir stringByAppendingPathComponent:dealImageURL.GBKEncodedString];
            gifImageView = [[SCGIFImageView alloc] initWithGIFFile:filePath];
            gifImageView.contentMode = UIViewContentModeScaleAspectFit;
        }
        gifImageView.frame = CGRectMake(0, 0, tempImageView.frame.size.width, tempImageView.frame.size.height);
        [tempImageView addSubview:gifImageView];
    } else {//普通图片
        tempImageView.image = dealImage;
    }
}

- (void)addGIFImageView
{
    
}

/***********************
 ASIHTTPRequest delegate
 ***********************/
/*下载失败*/
//- (void)requestFailed:(ASIHTTPRequest *)request
//{
//	NSLog(@"下载失败: %@", request.error);
//    [[TKAlertCenter defaultCenter] postAlertWithMessage:@"下载失败"];
//    dealImage = _image;
//    [self removeDownloadView];
//}

/*下载完成*/
//- (void)requestFinished:(ASIHTTPRequest *)request
//{
//    NSLog(@"requestFinished");
//    [self removeDownloadView];
//    
//    if (dealImageURL.length) {
//        NSString *filePath = [_downloadFileDir stringByAppendingPathComponent:dealImageURL.GBKEncodedString];
//        dealImage = [UIImage imageWithContentsOfFile:filePath];
//    }
//    
//	if (dealImage != nil) {
//		contentScrollView.maximumZoomScale = scale;
//		contentScrollView.minimumZoomScale = 0.5;
//		[self showImage];
//	} 
//}

/*请求得到响应，从头部获取图片信息*/
//- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
//{
//    if (fileLength == 0) {
//        fileLength = request.contentLength/1024.0/1024.0;
//    }
//}

- (void)setProgress:(float)newProgress
{
    progressBar.progress = newProgress;
    if (fileLength > 0) {
        progressLabel.text = [NSString stringWithFormat:@"%.2fM/%.2fM", fileLength * newProgress, fileLength];
    }
}


/*双击屏幕，放大图片到4倍或恢复原图大小*/
- (void)doubleTapImage
{
	if (dealImage != nil) {//图片加载成功
		//判定触摸点是否在图片内部
        CGPoint point = [doubleTapGR locationInView:tempImageView];//获取触摸点相对于image的坐标
        float tempX = tempImageView.frame.size.width;
        float tempY = tempImageView.frame.size.height;
        
        float pointX = point.x * contentScrollView.zoomScale;
        float pointY = point.y * contentScrollView.zoomScale;
        
        if (pointX > 0.0 && pointY > 0.0 && pointX < tempX && pointY < tempY) {
            if (contentScrollView.zoomScale >= scale) {//当前图片已经最大化
                [contentScrollView zoomToRect:[self getRectWithScale:1 andCenter:point] animated:YES];
            } else {//当前图片未最大化
                [contentScrollView zoomToRect:[self getRectWithScale:scale andCenter:point] animated:YES];
            }
        }
	}
}

- (CGRect)getRectWithScale:(float)scale1 andCenter:(CGPoint)center
{
    CGRect rect;
    rect.size.width = contentScrollView.frame.size.width/scale1;
    rect.size.height = contentScrollView.frame.size.height/scale1;
    rect.origin.x = center.x - rect.size.width/2;
    rect.origin.y = center.y - rect.size.height/2;
    return rect;
}

/*******************
 scrollView delegate
 *******************/
/*返回放缩对象*/
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
	return tempImageView;
}

/*缩放过程控制*/
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
	//当缩放到原图1/3以下结束动作时，标记退出浏览的意图
//	if (scrollView.zoomScale < 0.33) {
//		returnTag = YES;
//	}	
	//根据相对原图放大和缩小两种情况，定位图片位置
    
    if(scrollView.zoomScale <= 1.0) {
        CGFloat tempX = 0.0;
        CGFloat tempY = 0.0;
        CGFloat tempW = width * scrollView.zoomScale;
        CGFloat tempH = height * scrollView.zoomScale;
        if (tempW <= mainSize.width) {
            tempX = mainSize.width/2 - tempW/2.0;
        } else {
            tempX = 0;
        }
        
        if (tempH <= mainSize.height) {
            tempY = mainSize.height/2 - tempH/2.0;
        } else {
            tempY = 0;
        }
        tempImageView.frame = CGRectMake(tempX, tempY, tempW, tempH);
    } else {
        CGFloat tempX = 0.0;
        CGFloat tempY = 0.0;
        CGFloat tempW = width * scrollView.zoomScale;
        CGFloat tempH = height * scrollView.zoomScale;
        
        if (isWidthImage) {
            if (tempW >= mainSize.width) {
                tempX = 0.0;
            } else {
                tempX = mainSize.width/2 - tempW/2.0;
            }
            
            if (tempH >= mainSize.height) {
                tempY = 0.0;
            } else {
                tempY = mainSize.height/2 - tempH/2.0;
            }
        }
        tempImageView.frame = CGRectMake(tempX, tempY, tempW, tempH);
    }
}

/*缩放结束后的操作*/
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)atScale
{
//	if (returnTag && scale <= 0.5) {//如果一次操作中曾缩小到原图1/3以下，且后续没有放大到1/2以上，则直接退出浏览
//		[self dismissModalViewControllerAnimated:NO];
//	} else {
//		returnTag = NO;
//	}
    if (atScale < 1.0) {
        CGPoint point = CGPointMake(contentScrollView.frame.size.width, contentScrollView.frame.size.height);
        [contentScrollView zoomToRect:[self getRectWithScale:1 andCenter:point] animated:YES];
    }
}

/*******
 基本功能
 *******/
/*存储图片到相册*/
- (void)saveImage
{
	if (dealImage != nil) {
		UIImageWriteToSavedPhotosAlbum(dealImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
	}
}

/*存储结果提示*/
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
	if (error == nil) {
//		[[TKAlertCenter defaultCenter] postAlertWithMessage:@"已存储到相册" image:[UIImage imageNamed:@"image_save.png"]];
	} else {
//		[[TKAlertCenter defaultCenter] postAlertWithMessage:@"存储失败"];
	}
}

/*播放音频*/
- (void)playAudio
{
    if (_audioPath.length) {
//        [XDMP3Player play:_audioPath];
    }
}

@end
